/**
* 版权声明：厦门睿商网络科技有限公司 版权所有 违者必究
* 日    期：2020-02-17
*/
package com.rzico.order.entity;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.rzico.annotation.IgnoreSwaggerParameter;
import com.rzico.basics.entity.Member;
import com.rzico.core.entity.SysMenu;
import com.rzico.order.enumx.OrderPaymentStatusEnum;
import com.rzico.order.enumx.OrderShippingStatusEnum;
import com.rzico.order.enumx.OrderStatusEnum;
import com.rzico.order.model.OrderPaymentVo;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * <pre>
 *   销售单数据库对象
 * </pre>
 * @author Rzico Boot
 * @version 1.0
 */
@Data
@Table(name = "wx_order")
@JsonIgnoreProperties(value = {"handler"})
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Order implements Serializable{

    @ApiModelProperty(value = "")
    @Id
    protected Long id;

    @ApiModelProperty(value = "创建日期", hidden = true)
    protected java.util.Date createDate;

    @ApiModelProperty(value = "修改日期", hidden = true)
    protected java.util.Date modifyDate;

    @ApiModelProperty(value = "订单编号", hidden = true)
    protected String sn;

    @ApiModelProperty(value = "收货地址 id")
    protected Long receiverId;

    @ApiModelProperty(value = "运单号")
    protected String trackingNo;

    @ApiModelProperty(value = "地区")
    protected Integer areaId;

    @ApiModelProperty(value = "地区名称")
    protected String areaName;

    @ApiModelProperty(value = "地址")
    protected String address;

    @ApiModelProperty(value = "收货人")
    protected String consignee;

    @ApiModelProperty(value = "联系电话")
    protected String phone;

    @ApiModelProperty(value = "预约时间")
    protected java.util.Date hopeDate;

    @ApiModelProperty(value = "到期时间")
    protected java.util.Date expire;

    @ApiModelProperty(value = "交易佣金")
    protected java.math.BigDecimal fee;

    @ApiModelProperty(value = "运费(含楼层费)")
    protected java.math.BigDecimal freight;

    @ApiModelProperty(value = "楼层费")
    protected java.math.BigDecimal levelFreight;

    @ApiModelProperty(value = "是否已分配库存", hidden = true)
    protected Boolean isAllocatedStock;

    @ApiModelProperty(value = "买家留言")
    protected String memo;

    @ApiModelProperty(value = "调整金额")
    protected java.math.BigDecimal offsetAmount;

    @ApiModelProperty(value = "订单状态(0.未确认,1.已确认,2.已完成,3.已取消,4.已评价)")
    protected Integer orderStatus;

    @ApiModelProperty(value = "支付状态(0.未支付,1.已支付,2.待退款,3.已退款)")
    protected Integer paymentStatus;

    @ApiModelProperty(value = "配送状态(0.未发货,1.已发货,2.待退货,3.已退货)")
    protected Integer shippingStatus;

    @ApiModelProperty(value = "赠送金币")
    protected Long point;

    @ApiModelProperty(value = "活动优惠")
    protected java.math.BigDecimal discount;

    @ApiModelProperty(value = "商品合计金额")
    protected java.math.BigDecimal subPrice;

    @ApiModelProperty(value = "商品合计数量")
    protected BigDecimal subQuantity;

    @ApiModelProperty(value = "优惠券")
    protected Long couponCodeId;

    @ApiModelProperty(value = "购买会员")
    protected Long memberId;

    @ApiModelProperty(value = "是否删除")
    protected Boolean deleted;

    @ApiModelProperty(value = "配送方式(0.普通快递,1.到店核销,2.同城物流)")
    protected Integer shippingMethod;

    @ApiModelProperty(value = "订货方式(0.线上订单,1.人工报单,2.门店销售)")
    protected Integer orderMethod;

    @ApiModelProperty(value = "业务日期")
    protected java.util.Date orderDate;

    @ApiModelProperty(value = "预计送达时间")
    protected java.util.Date estimateDate;

    @ApiModelProperty(value = "是否分配佣金")
    protected Boolean isDistribution;

    @ApiModelProperty(value = "是否首单", hidden = true)
    protected Boolean isFirst;

    @ApiModelProperty(value = "伟度")
    protected Double lat;

    @ApiModelProperty(value = "经度")
    protected Double lng;

    @ApiModelProperty(value = "应付金额")
    protected java.math.BigDecimal amountPayable;

    @ApiModelProperty(value = "已付金额")
    protected java.math.BigDecimal amountPaid;

    @ApiModelProperty(value = "归属企业")
    protected Long enterpriseId;

    @ApiModelProperty(value = "销项税率（%）")
    protected java.math.BigDecimal tax;

    @ApiModelProperty(value = "所属企业")
    protected Long companyId;

    @ApiModelProperty(value = "礼品卡")
    protected Long giftCardId;

    @ApiModelProperty(value = "团购号")
    protected Long groupBuyId;

    @ApiModelProperty(value = "砍价号")
    protected Long bargainBuyId;

    @ApiModelProperty(value = "销售门店")
    protected Long shopId;

    @ApiModelProperty(value = "业务员(employee)")
    @Column(name = "operator")
    protected String operatorId;

    @ApiModelProperty(value = "1推荐会员")
    @Column(name = "promoter1")
    protected Long promoterId1;

    @ApiModelProperty(value = "2推荐会员")
    @Column(name = "promoter2")
    protected Long promoterId2;

    @ApiModelProperty(value = "1级代理")
    protected Long agentId1;

    @ApiModelProperty(value = "业绩奖1")
    protected java.math.BigDecimal rebate1;

    @ApiModelProperty(value = "业绩奖2")
    protected java.math.BigDecimal rebate2;

    @ApiModelProperty(value = "业绩奖2")
    protected java.math.BigDecimal agent1;

    @ApiModelProperty(value = "开票类型:0.不开票,1.增票,2.普票")
    protected Integer taxType;

    @ApiModelProperty(value = "配送时间")
    protected String weekTime;

    @ApiModelProperty(value = "所属部门")
    protected String officeId;

    @ApiModelProperty(value = "已开票")
    protected Boolean invoiced;

    @ApiModelProperty(value = "创建者", hidden = true)
    protected String createBy;

    @ApiModelProperty(value = "更新者", hidden = true)
    protected String modifyBy;

    /**
     *  会员
     */
    @JsonIgnore
    @IgnoreSwaggerParameter
    protected Member member;


    @ApiModelProperty(value = "订单明细")
    List<OrderItem> itemList = new ArrayList<>();

    @ApiModelProperty(value = "支付清单")
    List<OrderPaymentVo> paymentVo = new ArrayList<>();

    @ApiModelProperty(value = "订单促销")
    List<OrderPromotion> promotions = new ArrayList<>();

    //是否都不需要发货商品
    @JsonIgnore
    public boolean isAllVirtual() {
        for (OrderItem orderItem:getItemList()) {
            if (orderItem.getSubType().equals(0) || orderItem.getSubType().equals(1)) {
                return false;
            }
        }
        return true;
    }

    public List<OrderItem> sortItemList() {
        List<OrderItem> data = new ArrayList<>();
        data.addAll(getItemList());
        Collections.sort(data, new Comparator<OrderItem>() {
            public int compare(OrderItem n1, OrderItem n2) {

                return n1.getProductId().compareTo(n2.getProductId());
            }
        });
        return data;
    }

    public String getMemberName() {
        Member member = getMember();
        if (member!=null) {
            return member.getName();
        } else {
            return null;
        }
    }

    public String getMemberMobile() {
        Member member = getMember();
        if (member!=null) {
            return member.getMobile();
        } else {
            return null;
        }
    }

    @ApiModelProperty(hidden = true)
    @JsonIgnore
    public BigDecimal calculateSubQuantity(){
        BigDecimal totalQuantity = new BigDecimal(0);
        if (null != itemList && itemList.size() > 0){
            for (OrderItem orderItem : itemList){
                totalQuantity = totalQuantity.add(orderItem.getQuantity());
            }
        }
        return totalQuantity.setScale(2,BigDecimal.ROUND_HALF_DOWN);
    }

    @ApiModelProperty(hidden = true)
    @JsonIgnore
    public BigDecimal calculateSubPrice() {

        BigDecimal totalSubPrice = new BigDecimal(0);
        if (null != itemList && itemList.size() > 0){
            for (OrderItem orderItem : itemList){
                BigDecimal subPriceTotal = orderItem.getPrice().multiply(orderItem.getQuantity()).setScale(2,BigDecimal.ROUND_HALF_DOWN);
                totalSubPrice =  totalSubPrice.add(subPriceTotal);
            }
        }
        return totalSubPrice.setScale(2,BigDecimal.ROUND_HALF_DOWN);

    }

    @ApiModelProperty(hidden = true)
    @JsonIgnore
    public BigDecimal calculateNoPromotionSubPrice() {

        BigDecimal totalSubPrice = new BigDecimal(0);
        if (null != itemList && itemList.size() > 0){
            for (OrderItem orderItem : itemList){
                if (orderItem.getPromotionId()==null) {
                    BigDecimal subPriceTotal = orderItem.getPrice().multiply(orderItem.getQuantity()).setScale(2,BigDecimal.ROUND_HALF_DOWN);
                    totalSubPrice = totalSubPrice.add(subPriceTotal);
                }
            }
        }
        return totalSubPrice.setScale(2,BigDecimal.ROUND_HALF_DOWN);

    }

    @JsonIgnore
    public String getTitle() {
        for (OrderItem orderItem:getItemList()) {
            return orderItem.getName();
        }
        return null;
    }

    @ApiModelProperty(hidden = true)
    @JsonIgnore
    public BigDecimal calculatePaymentPaid() {

        BigDecimal paymentPaid = BigDecimal.ZERO;
        for (OrderPaymentVo vo:getPaymentVo()) {
            if (vo.getChk()) {
                paymentPaid = paymentPaid.add(vo.getAmount().setScale(2,BigDecimal.ROUND_HALF_DOWN));
            }
        }
        return paymentPaid.setScale(2,BigDecimal.ROUND_HALF_DOWN);

    }

    @ApiModelProperty(hidden = true)
    @JsonIgnore
    public BigDecimal calculateAmountPayable() {

        BigDecimal totalAmountPayable = calculateSubPrice();

        BigDecimal freight = null == this.freight?BigDecimal.ZERO : this.freight;
        BigDecimal offsetAmount = null == this.offsetAmount?BigDecimal.ZERO : this.offsetAmount;
        BigDecimal discount = null == this.discount?BigDecimal.ZERO : this.discount;
        // +加上运费 + 楼层费 - 抹零 - 优惠券抵扣 - 金币抵扣 - 提货券抵扣 - 营销折扣 - 纸质券抵扣金额 - 全场活动折扣
        totalAmountPayable = totalAmountPayable.add(freight).
                subtract(offsetAmount).subtract(discount);
        return totalAmountPayable.setScale(2,BigDecimal.ROUND_HALF_DOWN);

    }


    @ApiModelProperty(value = "订单状态")
    public String getStatusDescr() {
        if (getOrderStatus().equals(OrderStatusEnum.ORDER_STATUS_CANCLE.getId()) ) {
            return "已关闭";
        } else
        if (getOrderStatus().equals(OrderStatusEnum.ORDER_STATUS_UNCONFIRM.getId()) && getPaymentStatus().equals(OrderPaymentStatusEnum.PAYMENT_STATUS_UNPAY.getId()) ) {
            return "待付款";
        } else
        if (getOrderStatus().equals(OrderStatusEnum.ORDER_STATUS_UNCONFIRM.getId()) && getPaymentStatus().equals(OrderPaymentStatusEnum.PAYMENT_STATUS_PAY.getId()) ) {
            return "待确认";
        } else
        if (getShippingStatus().equals(OrderShippingStatusEnum.SHIPPING_STATUS_WAIT_REFUND_SHIPPING.getId()) ) {
            return "待退货";
        } else
        if (getPaymentStatus().equals(OrderPaymentStatusEnum.PAYMENT_STATUS_WAIT_REFUND.getId()) ) {
            return "待退款";
        } else
        if (getOrderStatus().equals(OrderStatusEnum.ORDER_STATUS_CONFIRM.getId()) && getShippingStatus().equals(OrderShippingStatusEnum.SHIPPING_STATUS_REFUND_SHIPPING.getId()) ) {
            return "已寄回";
        } else
        if (getOrderStatus().equals(OrderStatusEnum.ORDER_STATUS_CONFIRM.getId()) && getPaymentStatus().equals(OrderPaymentStatusEnum.PAYMENT_STATUS_REFUND.getId()) ) {
            return "已退款";
        } else
        if (getOrderStatus().equals(OrderStatusEnum.ORDER_STATUS_CONFIRM.getId()) && getShippingStatus().equals(OrderShippingStatusEnum.SHIPPING_STATUS_UNSHIPPNG.getId()) ) {
            return "待发货";
        } else
        if (getOrderStatus().equals(OrderStatusEnum.ORDER_STATUS_CONFIRM.getId()) && getShippingStatus().equals(OrderShippingStatusEnum.SHIPPING_STATUS_SHIPPNG.getId()) ) {
            return "已发货";
        } else
        if (getOrderStatus().equals(OrderStatusEnum.ORDER_STATUS_COMPLETE.getId()) && getPaymentStatus().equals(OrderPaymentStatusEnum.PAYMENT_STATUS_REFUND.getId()) ) {
            return "已退款";
        } else
        if (getOrderStatus().equals(OrderStatusEnum.ORDER_STATUS_REVIEWED.getId())) {
            return "交易成功";
        } else {
            return "交易成功";
        }
    }

    public void setStatusDescr(String value) {

    }

}
